# -*format='UTF-8'*-
import os

import serial


# SPI
def clean_flash(chip, channel):
    dos = 'esptool --chip ' + chip + ' --port ' + channel + ' erase_flash'
    os.system(dos)


def write_flash(chip, channel, baud, place, file):
    dos = 'esptool --chip ' + chip + ' --port ' + channel + ' --baud ' + baud + ' write_flash -z ' + place + ' ' + file
    os.system(dos)


def read_mac(channel):
    dos = 'esptool --port ' + channel + ' read_mac'
    os.system(dos)


# serial


def find_serial():
    os.system('python -m serial.tools.list_ports')


def serial_ready(channel, baud, timeout):
    device = ()
    try:
        device = serial.Serial(channel, baud, timeout=timeout)
    except Exception:
        pass
    return device


def open_serial(device):
    try:
        device.open()
    except Exception:
        pass
    flag = device.is_open()
    if flag:
        print('connect to the serial!')
        return True
    else:
        print('error to connect to the serial')
        return False


def close_serial(device):
    try:
        device.close()
    except Exception:
        pass
    flag = device.is_open()
    if not flag:
        print('disconnect to serial!')
        return device
    else:
        print('error to disconnect to the serial')
        return 0


def read_serial(device):
    flag = device.is_open()
    if flag:
        print('connect to the serial!\n')
        reads = device.read_all()
    else:
        print('error to connect to the serial!')
        return False
    return reads


def write_serial(device, text):
    flag = device.is_open()
    if flag:
        print('connect to the serial!\n')
        device.write(text.encode('utf-8'))
    else:
        print('error to connect to the serial!')
        return False
